package com.hup.utils.commons;

import com.hup.utils.commons.exception.AppCommonException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

/**
 * 需要依赖
 * <pre>
 <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-validator</artifactId>
     <version>5.2.4.Final</version>
 </dependency>

 <dependency>
     <groupId>javax.el</groupId>
     <artifactId>javax.el-api</artifactId>
     <version>3.0.0</version>
 </dependency>
 * </pre>
 * @author hugan
 * @date 2019/12/7
 */
public class ValidUtil {
    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T obj) {
        StringBuilder sb = new StringBuilder();
        Set<ConstraintViolation<T>> cvs = VALIDATOR.validate(obj, Default.class);
        for (ConstraintViolation<T> cv : cvs) {
            String message = cv.getMessage();
            sb.append(message);
            sb.append('\n');
        }
        if (sb.length() != 0) {
            throw new AppCommonException(sb.toString());
        }
    }

}
